package edu.whu.assignment7.controller;

import edu.whu.assignment7.entity.User;
import edu.whu.assignment7.exception.SelfException;
import edu.whu.assignment7.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/registration")
    public String registration(@RequestBody User user) throws SelfException{
        String username = user.getUsername();
        String password = user.getPassword();
        if(username.isEmpty() || password.isEmpty()) {
            throw new SelfException("参数错误");
        }
        int result = userService.registration(username, password);
        if(result == 1) {
            return "注册成功";
        }
        else {
            throw new SelfException("数据库存储错误");
        }
    }

    @PostMapping("/login")
    public String login(@RequestBody User user) throws SelfException {
        String username = user.getUsername();
        String password = user.getPassword();
        if(username.isEmpty() || password.isEmpty()) {
            throw new SelfException("参数错误");
        }
        int result = userService.login(username, password);
        if(result == 1) {
            return "登录成功";
        }
        return "登录失败";
    }
}
